package cn.cdzdjd.service.impl;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.text.StringEscapeUtils;
import org.json.JSONObject;
import org.jsoup.Connection.Response;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import cn.cdzdjd.exception.ErrorCode;
import cn.cdzdjd.exception.RenException;
import cn.cdzdjd.service.BaiduHaoKanService;
import cn.cdzdjd.util.JsoupUtil;
import cn.cdzdjd.util.UrlUtil;
import cn.cdzdjd.vo.VideoInfoVO;

@Service
public class BaiduHaoKanServiceImpl implements BaiduHaoKanService {
	private final String baseUrl = "https://haokan.hao123.com/v?vid=";
	@Resource
	private RestTemplate restTemplate;

	@Override
	public VideoInfoVO getVideoInfo(String url) {
		Response response = JsoupUtil.getUrlResponse(url);
		JsoupUtil.getDocument(url);
		Map<String, String> cookies = response.cookies();

		try {
			Map<String, String> map = UrlUtil.convertUrlParamsToMap(new URL(url));
			Response res = JsoupUtil.getResponseCookie(baseUrl + map.get("vid") + "&_format=json", cookies);
			String jsonStr = res.body();
			JSONObject json = new JSONObject(jsonStr);
			JSONObject curVideoMeta = json.getJSONObject("data").getJSONObject("apiData").getJSONObject("curVideoMeta");
			String title = curVideoMeta.getString("title");
			String videoTitle = StringEscapeUtils.unescapeJava(title);
			String poster = curVideoMeta.getString("poster");
			String posterUrl = StringEscapeUtils.unescapeJava(poster).split("\\@")[0];
			String video = curVideoMeta.getString("playurl");
			String videoUrl = StringEscapeUtils.unescapeJava(video);
			List<String> videoList = new ArrayList<>();
			videoList.add(UrlUtil.setHttps(videoUrl));
			List<String> posterList = new ArrayList<>();
			posterList.add(UrlUtil.setHttps(posterUrl));
			return new VideoInfoVO(videoList, posterList, videoTitle, null);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RenException(ErrorCode.PARSE_ERROR);
		}
	}

}
